import datetime
import shlex
import subprocess
import sys

from coin.exchange.bithumb.kr_rest_web.native_private_client import \
  BithumbWebNativePrivateClient

from absl import flags, app

FLAGS = flags.FLAGS

flags.DEFINE_list('noti_slack', '', 'Comma separated slack users or channel.')

flags.DEFINE_list('noti_email', '', 'Comma separated email.')

flags.DEFINE_string('cookie_file', None, '')

flags.DEFINE_integer(
    'day_offset',
    1,
    'Trigger alarm if expiration time of the lastest coupon is less than |day_offset|.')

flags.DEFINE_float('remain_ratio_offset',
                   0.9,
                   'Trigger alarm if a percentage of used qty is above than offset.')


def send_noti(title, msg=None, noti_slack=None, noti_email=None):
  if not (noti_slack or noti_email):
    return
  cmds = ['noti']
  for slack in FLAGS.noti_slack:
    cmds.extend(['-s', slack])

  for email in FLAGS.noti_email:
    cmds.extend(['-m', email])

  cmds.append(title)
  if msg:
    cmds.append(msg)
  subprocess.call(cmds)


def main(_):
  assert FLAGS.cookie_file

  client = BithumbWebNativePrivateClient(FLAGS.cookie_file)
  res = client.query_coupon_list(1)

  total_used_amt = 0
  total_remain_amt = 0
  end_dt = None
  num_available_coupon = 0

  for coupon in res.msg['lists']:
    if '만료' in coupon['STATUS']:
      continue

    num_available_coupon += 1
    total_used_amt += int(coupon['SUM_TRADE_PRICE'])
    total_remain_amt += int(coupon['TRADE_PRICE'])
    end_dt = datetime.datetime.strptime(coupon['END_DT'] + ' +0900', '%Y-%m-%d %H:%M:%S.%f %z')

  remain_days = datetime.timedelta(seconds=end_dt.timestamp()
                                   - datetime.datetime.now().timestamp()).days
  remain_ratio = float(total_used_amt) / float(total_remain_amt)

  if num_available_coupon == 0:
    title = 'Check coupon with cookie: ' + FLAGS.cookie_file
    content = ('No available coupons: ' + '\n' + ' '.join(map(shlex.quote, sys.argv)))

    print(title, content, "Alarm triggered.", sep='\n')
    send_noti(title, content, FLAGS.noti_slack, FLAGS.noti_email)
  elif remain_days <= FLAGS.day_offset:
    title = 'Check coupon with cookie: ' + FLAGS.cookie_file
    content = ('Check expiration date: ' + str(remain_days) + '\n'
               + ' '.join(map(shlex.quote, sys.argv)))

    print(title, content, "Alarm triggered.", sep='\n')
    send_noti(title, content, FLAGS.noti_slack, FLAGS.noti_email)
  elif remain_ratio >= FLAGS.remain_ratio_offset:
    title = 'Check coupon with cookie: ' + FLAGS.cookie_file
    content = (('Remaining amt is not sufficient: %f (%s/%s)' %
                (remain_ratio, format(total_used_amt, ','), format(total_remain_amt, ','))) + '\n'
               + ' '.join(map(shlex.quote, sys.argv)))

    print(title, content, "Alarm triggered.", sep='\n')
    send_noti(title, content, FLAGS.noti_slack, FLAGS.noti_email)
  else:
    print("Checked.")

  return 0


if __name__ == '__main__':
  app.run(main)
